package com.maimao.order.rabbit;

import com.maimao.order.config.RabbitProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author MaoLin Wang
 * @date 2021/1/18 6:05 下午
 */
@Service
@Slf4j
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 普通订单提交消息，超时未支付的消息进入死信队列，
     *
     * @param orderId 订单id
     */
    public void sendOrderCommitMessage(final Long orderId) {

        try {
            if (orderId != null && orderId > 0) {
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                rabbitTemplate.setExchange(RabbitProperties.ORDER_SUBMIT_EXCHANGE);
                rabbitTemplate.setRoutingKey(RabbitProperties.ORDER_SUBMIT_ROUTING_KEY);
                rabbitTemplate.convertAndSend(orderId, new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        MessageProperties properties = message.getMessageProperties();
                        /**
                         * 持久化：性能影响巨大
                         */
                        properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                        properties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME,Long.class);

                        //动态生成TTL
                        properties.setExpiration(RabbitProperties.PAY_EXPIRE);
                        return message;
                    }
                });
                log.info("下单发送消息==>{}", orderId);
            }
        } catch (Exception e) {
            log.error("下单发送消息异常:\ncause:{},\n{}", e.getCause(), e.getMessage());
        }
    }
}
